package com.youfan.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.youfan.entity.Useradmin;
import com.youfan.mapper.UserAdminMapper;
import com.youfan.page.CommonPage;
import com.youfan.service.UseradminService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class UseradminServiceImpl extends ServiceImpl<UserAdminMapper, Useradmin> implements UseradminService {
    Logger logger= LoggerFactory.getLogger(UseradminServiceImpl.class);
    private static final String KEY = "queryUseradmin";
    @Autowired
    private UserAdminMapper userAdminMapper;

    @Override
    public int insertOne(Useradmin useradmin) {
        useradmin.setCreateTime(new Date());
        useradmin.setStatus(1);
        return userAdminMapper.insert(useradmin);
    }
    @SentinelResource(value = KEY, blockHandler = "queryByCondtionBlockHandlerMethod", fallback = "queryByCondtionFallback")
    @Override
    public CommonPage<Useradmin> queryByCondtion(Useradmin useramdin) {
        PageHelper.startPage(useramdin.getPageNum(),useramdin.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if(StringUtils.isNotBlank(useramdin.getUsername())){
            queryWrapper.like("username", useramdin.getUsername());
        }
        if(StringUtils.isNotBlank(useramdin.getEmail())){
            queryWrapper.like("email", useramdin.getEmail());
        }
        if(StringUtils.isNotBlank(useramdin.getNickName())){
            queryWrapper.like("nick_name", useramdin.getNickName());
        }
        List<Useradmin> list = userAdminMapper.selectList(queryWrapper);
        return CommonPage.restPage(list);
    }
    @SentinelResource(value = KEY, blockHandler = "findByidHandler", fallback = "findByidFallback")
    @Override
    public Useradmin findByid(Useradmin useradmin) {
        return  userAdminMapper.selectById(useradmin.getId());
    }

    @Override
    public int updateOne(Useradmin useramdin) {
        return userAdminMapper.updateById(useramdin);
    }

    /**
     * 流量消峰控件
     */
    @PostConstruct
    public void initDegradeRule() {
        List<FlowRule> flowRules = new ArrayList<>();
        FlowRule flowRule = new FlowRule(KEY);
        // set limit qps to 20
        flowRule.setCount(20);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setLimitApp("default");
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);

        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(KEY);
        // 80s内调用接口出现异常次数超过5的时候, 进行熔断
        rule.setCount(5);
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        rule.setTimeWindow(80);
        rules.add(rule);


        DegradeRuleManager.loadRules(rules);
    }

    /**
     * 流量消峰
     * @param useramdin
     * @param e
     * @return
     */
    public Useradmin findByidHandler(Useradmin useramdin, BlockException e) {
        logger.info("UseradminServiceImpl findByidHandler"+ JSONObject.toJSONString(useramdin), e.toString());
        logger.info("流量超过限制，请稍后再试: " + useramdin.getId());

        Useradmin useradmin=new Useradmin();
        useradmin.setUsername("张三");
        useradmin.setPassword("123456");
        useradmin.setEmail("397237738@qq.com");
        useradmin.setNickName("阿财");
        return useradmin;

    }

    public Useradmin findByidFallback(Useradmin useramdin, Throwable e) {
        logger.info("UseradminServiceImpl findByidFallback"+ JSONObject.toJSONString(useramdin), e.toString());
        Useradmin useradmin=new Useradmin();
        useradmin.setUsername("张三");
        useradmin.setPassword("123456");
        useradmin.setEmail("397237738@qq.com");
        useradmin.setNickName("阿财");
        return useradmin;
    }

    /**
     * findByID流量消峰
     * @param useramdin
     * @param e
     * @return
     */
    public CommonPage<Useradmin> queryByCondtionBlockHandlerMethod(Useradmin useramdin, BlockException e) {
        logger.info("UseradminServiceImpl blockHandler"+ JSONObject.toJSONString(useramdin), e.toString());
        logger.info("流量超过限制，请稍后再试: " + useramdin.getId());
        List<Useradmin> list=new ArrayList<Useradmin>();
        Useradmin useradmin=new Useradmin();
        useradmin.setUsername("张三");
        useradmin.setPassword("123456");
        useradmin.setEmail("397237738@qq.com");
        useradmin.setNickName("阿财");
        list.add(useradmin);
        return CommonPage.restPage(list);

    }

    public CommonPage<Useradmin> queryByCondtionFallback(Useradmin useramdin, Throwable e) {
        logger.info("UseradminServiceImpl fallback"+ JSONObject.toJSONString(useramdin), e.toString());
        List<Useradmin> list=new ArrayList<Useradmin>();
        Useradmin useradmin=new Useradmin();
        useradmin.setUsername("张三");
        useradmin.setPassword("123456");
        useradmin.setEmail("397237738@qq.com");
        useradmin.setNickName("阿财");
        list.add(useradmin);
        return CommonPage.restPage(list);
    }
}
